package com.simple.framework.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.simple.business.domain.enumeration.ThirdAuthenticationEnum;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.enums.AuthResponseStatus;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthWeChatOpenRequest;
import me.zhyd.oauth.utils.HttpUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

@Slf4j
public class WeiXinLoginAuthRequest extends AuthWeChatOpenRequest {
    private static final String MINIPROGRAM_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
    private final ThirdAuthenticationEnum thirdAuthenticationEnum;
    public WeiXinLoginAuthRequest(AuthConfig config, ThirdAuthenticationEnum thirdAuthenticationEnum) {
        super(config);
        this.thirdAuthenticationEnum = thirdAuthenticationEnum;
    }

    public WeiXinLoginAuthRequest(AuthConfig config, AuthStateCache authStateCache) {
        super(config, authStateCache);
        this.thirdAuthenticationEnum = null;
    }

    private AuthResponse miniprogram(String code){

        String url = String.format(MINIPROGRAM_LOGIN_URL,config.getClientId(),config.getClientSecret(),code);
        String body = new HttpUtils(config.getHttpConfig()).get(url).getBody();
        JSONObject jsonObject = JSON.parseObject(body);
        // 用户信息:{"unionid":"ooRGh6uybWvMiGnEbTEFVmheRoKA",
        //          "openid":"ot6wg7WAOZadB4jR9DQ8FLqwh8zU",
        //          "session_key":"WiLEi58eMI3UYe9NYb0OLg=="}
        log.info("用户信息:{}",jsonObject);

        // //todo 测试环境
        // jsonObject = JSON.parseObject("{\"unionid\":\"ooRGh6uybWvMiGnEbTEFVmheRoKA\",\"openid\":\"ot6wg7WAOZadB4jR9DQ8FLqwh8zU\",\"session_key\":\"WiLEi58eMI3UYe9NYb0OLg==\"}");

        if (!jsonObject.containsKey("errcode")){
            AuthUser user = AuthUser.builder()
                    .rawUserInfo(jsonObject)
                    .nickname("小程序用户"+ RandomStringUtils.randomAlphabetic(6))
                    .uuid(jsonObject.getString("unionid"))
                    .source(source.toString())
                    .build();
            return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(user).build();
        }
        return AuthResponse.builder().code(AuthResponseStatus.FAILURE.getCode()).msg(jsonObject.getString("errmsg")).build();
    }

    @Override
    public AuthResponse login(AuthCallback authCallback) {
        if(thirdAuthenticationEnum != null && thirdAuthenticationEnum == ThirdAuthenticationEnum.WEI_XIN_MINIPROGRAM){
            // 小程序授权
            return miniprogram(authCallback.getCode());
        }
        return super.login(authCallback);

    }

    @Override
    protected AuthUser getUserInfo(AuthToken authToken) {
        AuthUser userInfo = super.getUserInfo(authToken);
        log.info("用户信息:{}",userInfo.getRawUserInfo());
        String unionId = userInfo.getRawUserInfo().getString("unionid");
        if(StringUtils.isBlank(unionId)){
            throw new RuntimeException("获取unionid失败");
        }
        userInfo.setUuid(unionId);
        userInfo.setRemark(authToken.getOpenId());
        return userInfo;
    }

}
